package com.health.common.service.util;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.health.common.common.ErrorCode;
import com.health.common.exception.BusinessException;
import com.health.common.model.vo.UserKeyVO;
import com.health.common.service.config.SystemConfig;
import com.health.common.utils.IOUtil;
import jakarta.annotation.Resource;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

/**
 * Http方式请求WeBASE-Front
 */
@Service
public class WeBASEUtils {


    @Value("${webase.url}")
    private String webaseUrl;

    /**
     * 发送 post 请求调用链接口
     * @param userAddress
     * @param funcName
     * @param funcParam
     * @return 请求结果
     */
    public String funcPost(String userAddress, String funcName, List funcParam,String ABI,String BIN,String contractAddress) {

        JSONArray abiJSON = JSONUtil.parseArray(ABI);
        //负载
        JSONObject data = JSONUtil.createObj();
        data.set("groupId", "1");
        data.set("contractPath", "/");
        data.set("contractAbi", abiJSON);
        data.set("useAes", false);
        data.set("useCns", false);
        data.set("cnsName", "");
        data.set("user", userAddress);
        data.set("contractAddress", contractAddress);
        data.set("funcName", funcName);
        data.set("funcParam", funcParam);

        String dataString = JSONUtil.toJsonStr(data);

        // 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建post请求方式实例
        HttpPost httpPost = new HttpPost(webaseUrl+"/trans/handle");
        // 设置请求头 发送的是json数据格式
        httpPost.setHeader("Content-type", "application/json;charset=utf-8");
        // 设置参数---设置消息实体 也就是携带的数据
        StringEntity entity = new StringEntity(dataString, Charset.forName("UTF-8"));
        // 设置编码格式
        entity.setContentEncoding("UTF-8");
        // 发送Json格式的数据请求
        entity.setContentType("application/json");
        // 把请求消息实体塞进去
        httpPost.setEntity(entity);
        // 执行http的post请求
        CloseableHttpResponse httpResponse;
        String result = null;

        try {
            httpResponse = httpClient.execute(httpPost);
            result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(result);
        return result;
    }

    /**
     * 向webasefront里面注册用户
     */
    public UserKeyVO regBlockChainUser(String userName){
        int randomNum = RandomUtil.getRandom().nextInt(Integer.MAX_VALUE);
        String privateKeyRegUrl = String.format("%s/privateKey?useAes=false&type=0&userName=%s&groupId=group0",webaseUrl,userName+randomNum);
        //发送get请求
        String result = HttpUtil.get(privateKeyRegUrl);
        //如果为空，抛出异常
        if (result == null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //判断jsonobject里面是否有code这个key
        if (jsonObject.containsKey("code")){
            //判断code是否为0
            if (jsonObject.getInt("code") == 500){
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }
        if (!jsonObject.containsKey("privateKey") && !jsonObject.getStr("privateKey").isEmpty()){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        if (jsonObject.containsKey("errorMessage")){
            String errorMessage = jsonObject.getStr("errorMessage");
            if (errorMessage.equalsIgnoreCase("user name already exists")){
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }
        String privateKey = getPrivateKey(userName + randomNum);
        UserKeyVO userKeyVO = new UserKeyVO();
        userKeyVO.setPrivateKey(privateKey);
        userKeyVO.setPublicKey(jsonObject.getStr("publicKey"));
        userKeyVO.setAddress(jsonObject.getStr("address"));
        return userKeyVO;
    }

    public String getPrivateKey(String userName) {
        String localKeyStoresUrl = String.format("%s/privateKey/localKeyStores",webaseUrl);
        String result = HttpUtil.get(localKeyStoresUrl);
        //如果为空，抛出异常
        if (result == null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        JSONArray jsonArray = JSONUtil.parseArray(result);
        if (jsonArray.isEmpty()){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        //把jsonArray里面的元素都转成JsonObject对象，然后遍历，判断里面有没有userName
        for (Object o : jsonArray) {
            JSONObject jsonObject = JSONUtil.parseObj(o);
            if (userName.equalsIgnoreCase(jsonObject.getStr("userName"))){
                return jsonObject.getStr("privateKey");
            }
        }
        throw new BusinessException(ErrorCode.SYSTEM_ERROR);
    }




}
